package com.promise.jokerdream.response.parser

import com.promise.jokerdream.response.phone.PenguinShareXmlResponse
import org.jsoup.Jsoup

/**
 * 企鹅分享XML解析器
 * 专门用于解析大乐斗企鹅分享相关的XML数据
 * 基于Jsoup实现
 */
class PenguinShareXmlParser : BaseXmlParser<PenguinShareXmlResponse>() {
    
    /**
     * 解析企鹅分享XML数据
     * @param xmlString XML字符串
     * @return 解析结果
     */
    fun parsePenguinShareXml(xmlString: String): XmlParseResult<PenguinShareXmlResponse> {
        return parseXml(xmlString)
    }
    
    /**
     * 实现基类的具体解析逻辑
     * @param xmlString XML字符串
     * @return 解析后的企鹅分享数据
     */
    override fun doParse(xmlString: String): PenguinShareXmlResponse {
        return try {
            val doc = Jsoup.parse(xmlString)
            val divElement = doc.selectFirst("div#id")
            
            if (divElement != null) {
                val html = divElement.html()
                val text = divElement.text()
                
                // 提取第一个<p>标签后面的文本内容
                // 使用正则表达式匹配 <p>【历程分享】</p> 后面的文本内容
                val limitMessageRegex = Regex("<p>【历程分享】</p>\\s*([^<]+)")
                val limitMessageMatch = limitMessageRegex.find(html)
                val actionResult = limitMessageMatch?.groupValues?.get(1)?.trim() ?: ""
                
                // 解析今日分享次数 (格式: "今日分享次数：10/10")
                val todayShareCountRegex = Regex("今日分享次数：(\\d+)/(\\d+)")
                val todayShareCountMatch = todayShareCountRegex.find(text)
                val todayShareCurrent = todayShareCountMatch?.groupValues?.get(1)?.toIntOrNull() ?: 0
                val todayShareMax = todayShareCountMatch?.groupValues?.get(2)?.toIntOrNull() ?: 0
                
                PenguinShareXmlResponse(
                    actionResult = actionResult,
                    todayShareCurrent = todayShareCurrent,
                    todayShareMax = todayShareMax
                )
            } else {
                // 如果找不到div#id，返回默认值
                PenguinShareXmlResponse(
                    actionResult = "解析失败",
                    todayShareCurrent = 0,
                    todayShareMax = 0
                )
            }
        } catch (e: Exception) {
            // 解析异常时返回默认值
            PenguinShareXmlResponse(
                actionResult = "解析异常: ${e.message}",
                todayShareCurrent = 0,
                todayShareMax = 0
            )
        }
    }
}